import { useCallback, useMemo, useRef, useState } from 'react'
import { HsAdminInput } from '@hs-admin/base-components'
import { Button, Spin, Table } from 'antd'
import { initPageType, message, usePageChange } from '@hs-admin/utils'
import { importOneId, queryData } from '@/api/batchQuery.ts'

const initPage: initPageType = {
  current: 1,
  total: 0,
  pageSize: 10
}

export const useAddBySearch = (theId: string, tableId: string, columns: Array<any>, resetCall: () => void) => {
  const [tempKeywords, setTempKeywords] = useState('')

  const keywords = useRef('')

  const [data, setData] = useState([])

  const getFields = useCallback(
    async (page: number, pageSize: number) => {
      const res = await queryData(tableId, {
        page,
        page_size: pageSize,
        keywords: keywords.current || null,
        filters: [],
        ids: null
      })
      setData(res.items)
      return res.total
    },
    [tableId]
  )

  const { resetPageAndTriggerRequest, pagination, loading } = usePageChange(initPage, getFields)

  return useMemo(
    () => ({
      children: (
        <Spin spinning={loading}>
          <div className="flex flex-col gap-4">
            <div className="flex gap-4 items-center">
              <HsAdminInput
                value={tempKeywords}
                onChange={(e: any) => {
                  setTempKeywords(e.target.value)
                }}
                className="w-96"
                placeholder="请输入搜索内容"
              />
              <Button
                type="primary"
                onClick={() => {
                  keywords.current = tempKeywords
                  resetPageAndTriggerRequest()
                }}>
                搜索
              </Button>
            </div>
            <div className="flex items-center gap-4 w-full">
              <Button
                type="primary"
                disabled={pagination.current === 1}
                onClick={() => {
                  pagination.onChange(pagination.current - 1)
                }}>
                上一页
              </Button>
              <span>
                第{pagination.current}页 / 共{Math.ceil(pagination.total / pagination.pageSize)}页
              </span>
              <Button
                type="primary"
                disabled={pagination.current * pagination.pageSize >= pagination.total}
                onClick={() => {
                  pagination.onChange(pagination.current + 1)
                }}>
                下一页
              </Button>
              <span>每页{pagination.pageSize}条</span>
            </div>
            <Table
              pagination={false}
              columns={[
                {
                  title: '',
                  key: 'doChoose',
                  width: 70,
                  fixed: 'left',
                  render: (_, row) => (
                    <Button
                      type="link"
                      onClick={() => {
                        importOneId(theId, {
                          data_id: row.id
                        }).then(() => {
                          message.success('添加成功')
                        })
                      }}>
                      添加
                    </Button>
                  )
                },
                ...columns
              ]}
              dataSource={data}
            />
          </div>
        </Spin>
      ),
      onOk: () => {
        console.log('确认')
      },
      onCancel: () => {
        console.log('取消')
        resetCall()
      },
      title: '搜索添加',
      onOpen: () => {
        setData([])
        setTempKeywords('')
        keywords.current = ''
        resetPageAndTriggerRequest()
      }
    }),
    [columns, data, pagination, resetCall, resetPageAndTriggerRequest, tempKeywords, theId]
  )
}
